import Vue from 'vue'
import ElementUI from 'element-ui'
import JSZip from 'jszip'
import config from '@/config'
import { Common } from 'cby.assist'
let loading = null
/** 下载接口地址 */
const DOWNLOAD_API = `${config.services.system || ''}/download`

/**
 * Vue组件文件下载功能
 */
Vue.prototype.$download = ({ name, storage, bucket }) => download(`${DOWNLOAD_API}?name=${name}&storage=${storage}&bucket=${bucket}`)

/**
 * 通用文件下载地址
 */
export const downloadUrl = ({ name, storage, bucket }) => `${config.baseUrl}${DOWNLOAD_API}?name=${name}&storage=${storage}&bucket=${bucket}&token=${localStorage.getItem('token')}`

/**
 * 通用文件下载功能
 */
export const download = (url, params) => {
  if (!url.startsWith('http')) {
    url = config.baseUrl + url
  }
  if (!params) {
    params = {}
  }
  params.token = localStorage.getItem('token')
  url = Common.parseParam(url, params)
  window.open(url)
}

/**
 * 批量下载图片
 */
export const downloadZip = async(sourceList, zipName = '默认文件') => {
  if (loading !== false) {
    loading = ElementUI.Loading.service({
      background: 'rgba(255, 255, 255, 0.1)'
    })
  }
  const zip = new JSZip()
  const fileFolder = zip.folder(zipName) // 创建文件夹
  const fileList = []
  for (let i = 0; i < sourceList.length; i++) {
    const name = sourceList[i].name // 每张图片的名称
    const image = new Image()
    image.setAttribute('crossOrigin', 'Anonymous') // 设置crossOrigin属性，解决图片跨域报错
    image.src = sourceList[i].src
    image.onload = async() => {
      const url = await getImageBase64(image)
      fileList.push({ name: name, img: url.substring(22) }) // 截取data:image/png;base64后的数据
      if (fileList.length === sourceList.length) {
        for (let k = 0; k < fileList.length; k++) {
          fileFolder.file(fileList[k].name + '.jpg', fileList[k].img, {
            base64: true
          })
        }
        zip.generateAsync({ type: 'blob' }).then(content => {
          downloadFile(content, zipName)
          if (loading) {
            loading.close()
          }
        })
      }
    }
    image.onerror = () => {
      fileList.push({ name: name, img: null })
      if (fileList.length === sourceList.length) {
        for (let k = 0; k < fileList.length; k++) {
          fileFolder.file(fileList[k].name + '.jpg', fileList[k].img, {
            base64: true
          })
        }
        zip.generateAsync({ type: 'blob' }).then(content => {
          downloadFile(content, zipName)
          if (loading) {
            loading.close()
          }
        })
      }
    }
  }
}

// 获取图片的base64编码
export const getImageBase64 = image => {
  const canvas = document.createElement('canvas')
  canvas.width = image.width
  canvas.height = image.height
  const ctx = canvas.getContext('2d')
  ctx.drawImage(image, 0, 0, image.width, image.height)
  // 获取图片后缀名
  const extension = image.src
    .substring(image.src.lastIndexOf('.') + 1)
    .toLowerCase()
  return canvas.toDataURL('image/' + extension, 1)
}

// 下载blob文件
export const downloadFile = (blob, fileName) => {
  const downloadElement = document.createElement('a')
  // 创建下载的链接
  const href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  // 下载后文件名
  downloadElement.download = fileName
  document.body.appendChild(downloadElement)
  // 点击下载
  downloadElement.click()
  // 下载完成移除元素
  document.body.removeChild(downloadElement)
  // 释放掉blob对象
  window.URL.revokeObjectURL(href)
}
/**
 * 注册Vue窗体拖拽指令，在窗体标签上写上v-drag就可以使用拖拽
 */
Vue.directive('drag', {
  bind: el => {},
  inserted: el => {
    el.onmousedown = e => {
      const disx = e.pageX - el.offsetLeft
      const disy = e.pageY - el.offsetTop
      document.onmousemove = e => {
        el.style.left = e.pageX - disx + 'px'
        el.style.top = e.pageY - disy + 'px'
      }
      document.onmouseup = () => document.onmousemove = document.onmouseup = null
    }
  },
  updated: el => {}
})

/**
 * 根据ID查询名称
 *
 * @param id
 *            查询编号
 * @param list
 *            查询列表
 * @param idField
 *            编号字段名
 * @param nameField
 *            名称字段名
 * @param childrenField
 *            子集字段名
 * @return 名称
 *
 */
Vue.prototype.$findName = (id, list, idField, nameField = 'name', childrenField) => {
  let name = ''
  const item = Common.recursiveQuery(id, list, idField)
  if (item != null && item[nameField]) {
    name = item[nameField]
  }
  return name
}

/**
 * 获取最大高度限制范围
 *
 * @param height
 *            限制高度
 * @return 高度
 *
 */
Vue.prototype.$limitHeight = (height = 0) => {
  const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
  let limit = (windowHeight || 0) - height
  if (limit < 0) {
    limit = 0
  }
  return limit
}
